const http = require('http')
const url = require('url')
const routes = require('./module/route')
const ejs = require('ejs')

http.createServer(function (req, res) {
  
  // 创建静态web服务
  routes.static(req, res, 'static')
  // 路由
  let pathname = url.parse(req.url).pathname

  // 获取请求类型
  console.log(req.method)

  if (pathname == '/login') {
    // let msg = '数据库里获取的数据'
    // let list = [
    //   { title: '新闻111'},
    //   { title: '新闻222'},
    //   { title: '新闻333'},
    //   { title: '新闻444'},
    //   { title: '新闻555'},
    // ]
    // ejs.renderFile('./views/login.ejs', { msg, list }, (err, data) => {
    //   if (err) {
    //     console.log(err)
    //   }
    //   res.writeHead(200, {'Content-Type' : 'text/html;charset="utf-8"'})
    //   res.end(data)
    // })

    // post请求
    ejs.renderFile('./views/form.ejs', { }, (err, data) => {
      res.writeHead(200, {'Content-Type' : 'text/html;charset="utf-8"'})
      res.end(data)
    })

  }else if (pathname == '/doLogin') {
    // 获取post传值
    let postData = ''
    req.on('data', (chunk) => {
      postData += chunk
    })
    req.on('end', () => {
      console.log(postData)
      res.end(postData)
    })
  } else if (pathname == '/news') {
    // 获取get传值
    var query = url.parse(req.url, true).query
    console.log(query)
    res.writeHead(200, {'Content-Type' : 'text/html;charset="utf-8"'})
    res.end('get传值获取成功')
  }

}).listen(8081)

console.log('http://localhost:8081')